import { DataTypes, Model, type Optional } from 'sequelize'
import sequelize from '../config'

// 帖子属性接口
export interface PostAttributes {
  id: number
  title: string
  content: string
  authorId: number
  viewCount: number
  likeCount: number
  replyCount: number
  isPinned: boolean
  isLocked: boolean
  createdAt?: Date
  updatedAt?: Date
}

// 创建帖子时的可选属性
export type PostCreationAttributes = Optional<PostAttributes, 'id' | 'viewCount' | 'likeCount' | 'replyCount' | 'isPinned' | 'isLocked' | 'createdAt' | 'updatedAt'>

// 帖子模型类
export class Post extends Model<PostAttributes, PostCreationAttributes> implements PostAttributes {
  declare id: number
  declare title: string
  declare content: string
  declare authorId: number
  declare viewCount: number
  declare likeCount: number
  declare replyCount: number
  declare isPinned: boolean
  declare isLocked: boolean
  declare readonly createdAt: Date
  declare readonly updatedAt: Date
}

// 定义帖子模型
Post.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    title: {
      type: DataTypes.STRING(255),
      allowNull: false,
      comment: '帖子标题'
    },
    content: {
      type: DataTypes.TEXT,
      allowNull: false,
      comment: '帖子内容'
    },
    authorId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      comment: '作者用户ID'
    },
    viewCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '浏览次数'
    },
    likeCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '点赞数量'
    },
    replyCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '回复数量'
    },
    isPinned: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      comment: '是否置顶'
    },
    isLocked: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
      comment: '是否锁定'
    }
  },
  {
    sequelize,
    tableName: 'posts',
    timestamps: true,
    indexes: [
      {
        fields: ['authorId']
      },
      {
        fields: ['isPinned']
      },
      {
        fields: ['createdAt']
      }
    ]
  }
)

export default Post
